import os
import dashscope
from typing import List, Dict, Any
import json
from datetime import datetime


class BusinessCommentAnalyzer:
    """电商评论分析系统 - 使用本地环境变量API密钥"""

    def __init__(self, api_key: str = None):
        """初始化评论分析器

        Args:
            api_key: 可选的API密钥，如果为None则从环境变量获取
        """
        # 优先使用传入的api_key，如果没有则从环境变量获取
        self.api_key = api_key or os.environ.get('DASHSCOPE_API_KEY')
        self._validate_and_set_api_key()
        self.analysis_history = []
        print("🚀 电商评论分析系统初始化完成")

    def _validate_and_set_api_key(self):
        """验证并设置API密钥"""
        if not self.api_key:
            raise ValueError("DASHSCOPE_API_KEY环境变量未设置，请设置有效的API密钥")

        dashscope.api_key = self.api_key
        print("✅ API密钥配置成功")

    def analyze_single_comment(self, comment: str) -> Dict[str, Any]:
        """分析单条评论"""
        try:
            from dashscope import Generation

            prompt = f"""
            请分析以下电商评论，提供详细的情感分析和产品特征提取：

            评论内容："{comment}"

            请以JSON格式返回分析结果，包含以下字段：
            - sentiment_analysis: 情感分析（包含overall_sentiment和confidence）
            - product_features: 产品特征列表（每个特征包含feature和sentiment）
            - intent_analysis: 用户意图分析（包含purchase_intent和urgency_level）
            """

            response = Generation.call(
                model='qwen-plus',
                prompt=prompt,
                result_format='message'
            )

            if response.status_code == 200:
                analysis_result = self._parse_analysis_response(response, comment)
                self.analysis_history.append(analysis_result)
                return analysis_result
            else:
                return {
                    "error": f"API调用失败: {response.message}",
                    "original_comment": comment
                }

        except Exception as e:
            return {
                "error": f"分析过程中出现异常: {str(e)}",
                "original_comment": comment
            }

    def _parse_analysis_response(self, response, original_comment: str) -> Dict[str, Any]:
        """解析API响应并生成模拟分析结果"""
        # 模拟分析逻辑 - 实际使用时应该解析真实的API响应
        comment_lower = original_comment.lower()

        # 情感分析
        if any(word in comment_lower for word in ['很棒', '很好', '满意', '推荐', '不错']):
            sentiment = "positive"
            confidence = 0.85
        elif any(word in comment_lower for word in ['很差', '失望', '问题', '投诉', '不好']):
            sentiment = "negative"
            confidence = 0.75
        else:
            sentiment = "neutral"
            confidence = 0.60

        # 产品特征提取
        features = []
        feature_keywords = {
            '屏幕': ['屏幕', '显示', '色彩'],
            '电池': ['电池', '续航', '电量'],
            '物流': ['物流', '快递', '配送'],
            '客服': ['客服', '服务', '态度'],
            '价格': ['价格', '价钱', '价位'],
            '外观': ['外观', '设计', '漂亮'],
            '功能': ['功能', '操作', '使用']
        }

        for feature, keywords in feature_keywords.items():
            if any(keyword in comment_lower for keyword in keywords):
                features.append({
                    "feature": feature,
                    "sentiment": "positive" if '很棒' in comment_lower or '很好' in comment_lower else "neutral"
                })

        # 意图分析
        if '推荐' in comment_lower or '满意' in comment_lower:
            purchase_intent = "recommend"
            urgency_level = "low"
        elif '投诉' in comment_lower or '问题' in comment_lower:
            purchase_intent = "complain"
            urgency_level = "high"
        else:
            purchase_intent = "neutral"
            urgency_level = "medium"

        return {
            "original_comment": original_comment,
            "sentiment_analysis": {
                "overall_sentiment": sentiment,
                "confidence": confidence
            },
            "product_analysis": {
                "product_features": features
            },
            "intent_analysis": {
                "purchase_intent": purchase_intent,
                "urgency_level": urgency_level
            },
            "analysis_timestamp": datetime.now().isoformat()
        }

    def batch_analyze_comments(self, comments: List[str]) -> List[Dict[str, Any]]:
        """批量分析评论"""
        results = []
        print(f"📊 开始批量分析 {len(comments)} 条评论...")

        for i, comment in enumerate(comments, 1):
            print(f"🔍 正在分析第 {i}/{len(comments)} 条评论...")
            result = self.analyze_single_comment(comment)
            results.append(result)

            # 添加短暂延迟避免API限制
            import time
            time.sleep(0.5)

        return results

    def _generate_summary_insights(self, results: List[Dict[str, Any]]) -> List[str]:
        """生成总结性洞察 - 修正了f-string语法问题"""
        insights = []

        # 分析产品特征分布
        common_features = {}
        for result in results:
            if "error" not in result:
                features = result.get("product_analysis", {}).get("product_features", [])
                for feature in features:
                    feat_name = feature.get("feature", "")
                    if feat_name:
                        common_features[feat_name] = common_features.get(feat_name, 0) + 1

        # 识别最常被提及的问题 - 使用变量避免f-string嵌套
        if common_features:
            top_issues = sorted(common_features.items(), key=lambda x: x[1], reverse=True)[:3]
            if top_issues:
                top_issue_names = [issue[0] for issue in top_issues]
                insights.append(f"最常见的产品关注点: {', '.join(top_issue_names)}")

        # 情感分布分析
        sentiment_dist = {}
        for result in results:
            if "error" not in result:
                sentiment = result.get("sentiment_analysis", {}).get("overall_sentiment", "unknown")
                sentiment_dist[sentiment] = sentiment_dist.get(sentiment, 0) + 1

        # 分析情感趋势
        positive_count = sentiment_dist.get("positive", 0)
        negative_count = sentiment_dist.get("negative", 0)
        neutral_count = sentiment_dist.get("neutral", 0)

        total_analyzed = len([r for r in results if "error" not in r])
        if total_analyzed > 0:
            positive_percent = (positive_count / total_analyzed) * 100
            negative_percent = (negative_count / total_analyzed) * 100

            if positive_count > negative_count:
                insights.append(f"整体客户反馈偏向积极 ({positive_percent:.1f}%正面)，产品满意度较高")
            elif negative_count > positive_count:
                insights.append(f"存在较多负面反馈 ({negative_percent:.1f}%负面)，需要重点关注客户投诉问题")
            else:
                insights.append("客户反馈呈现中性平衡，需进一步优化产品体验")

        # 紧急问题统计
        urgent_issues = 0
        for result in results:
            if "error" not in result:
                if result.get("intent_analysis", {}).get("urgency_level") == "high":
                    urgent_issues += 1

        if urgent_issues > 0:
            insights.append(f"发现{urgent_issues}个紧急问题，建议立即处理")

        # 总体分析统计
        successful_analysis = len([r for r in results if "error" not in r])
        error_count = len([r for r in results if "error" in r])

        if successful_analysis > 0:
            insights.append(
                f"分析完成度: {successful_analysis}/{len(results)} 条评论 ({successful_analysis / len(results) * 100:.1f}%)")

        return insights

    def export_analysis_report(self, results: List[Dict[str, Any]], filename: str = "analysis_report.json"):
        """导出分析报告"""
        report = {
            "analysis_summary": {
                "total_comments": len(results),
                "successful_analysis": len([r for r in results if "error" not in r]),
                "failed_analysis": len([r for r in results if "error" in r]),
                "generated_at": datetime.now().isoformat()
            },
            "detailed_results": results,
            "summary_insights": self._generate_summary_insights(results)
        }

        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(report, f, ensure_ascii=False, indent=2)

        print(f"📄 分析报告已导出至: {filename}")
        return report

    def get_system_status(self) -> Dict[str, Any]:
        """获取系统状态"""
        return {
            "api_key_configured": bool(self.api_key),
            "total_analysis_history": len(self.analysis_history),
            "last_analysis_time": self.analysis_history[-1].get(
                "analysis_timestamp") if self.analysis_history else None,
            "system_version": "1.0.0"
        }


def main():
    """主函数：测试运行评论分析系统"""
    print("=" * 60)
    print("🛍️  电商评论分析系统 - 测试运行")
    print("=" * 60)

    # 测试评论数据集
    test_comments = [
        "这款手机屏幕显示效果很棒，色彩鲜艳，但是电池续航有点短，希望能改进",
        "物流速度很快，包装也很完好，产品质量不错，性价比很高",
        "客服态度很差，等了很久都没人回复，产品也有质量问题，非常失望",
        "外观设计很漂亮，使用起来也很流畅，就是价格稍微有点贵",
        "功能齐全，操作简单，适合老年人使用，非常满意这次购物",
        "快递员服务态度很好，送货上门，产品使用体验也不错",
        "产品质量有问题，用了两天就坏了，售后服务也不到位",
        "性价比超高，功能强大，外观时尚，强烈推荐给大家",
        "物流太慢了，等了一个星期才到，而且包装有破损",
        "客服很耐心解答问题，产品使用效果很好，会再次购买"
    ]

    try:
        # 初始化分析器 - 自动从环境变量获取API密钥
        analyzer = BusinessCommentAnalyzer()

        print(f"\n📋 测试数据集: {len(test_comments)} 条代表性评论")
        print("包含电子产品、物流服务、客户投诉、外观设计等多种类型")

        # 执行批量分析
        results = analyzer.batch_analyze_comments(test_comments)

        # 生成总结洞察
        insights = analyzer._generate_summary_insights(results)

        print("\n" + "=" * 60)
        print("📈 分析结果总结报告")
        print("=" * 60)

        for i, insight in enumerate(insights, 1):
            print(f"{i}. {insight}")

        # 显示详细统计
        successful = len([r for r in results if "error" not in r])
        failed = len([r for r in results if "error" in r])

        print(f"\n📊 分析统计:")
        print(f"   ✅ 成功分析: {successful} 条评论")
        print(f"   ❌ 分析失败: {failed} 条评论")
        print(f"   📈 成功率: {successful / len(results) * 100:.1f}%")

        # 导出报告
        report_filename = f"business_analysis_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
        analyzer.export_analysis_report(results, report_filename)

        # 显示系统状态
        status = analyzer.get_system_status()
        print(f"\n🖥️  系统状态:")
        print(f"   🔑 API密钥配置: {'✅ 已配置' if status['api_key_configured'] else '❌ 未配置'}")
        print(f"   📚 历史分析记录: {status['total_analysis_history']} 条")

        print("\n🎯 测试运行完成！系统已就绪，可以处理实际评论数据。")

    except ValueError as e:
        print(f"\n❌ 系统初始化失败: {e}")
        print("\n💡 环境变量配置指南:")
        print("   1. Windows命令提示符:")
        print("      set DASHSCOPE_API_KEY=your_actual_api_key")
        print("   2. Windows PowerShell:")
        print("      $env:DASHSCOPE_API_KEY='your_actual_api_key'")
        print("   3. Linux/Mac终端:")
        print("      export DASHSCOPE_API_KEY=your_actual_api_key")
        print("   4. 永久设置（Linux/Mac）:")
        print("      在 ~/.bashrc 或 ~/.zshrc 中添加: export DASHSCOPE_API_KEY=your_actual_api_key")
        print("\n⚠️  安全提示: 不要在代码中硬编码API密钥")

    except Exception as e:
        print(f"\n❌ 运行过程中出现异常: {e}")
        print("请检查网络连接和API密钥有效性")


if __name__ == "__main__":
    main()
